package com.example.mqttmanage.config; // 确保包名正确

import com.example.mqttmanage.config.JwtTokenFilter; // 确保导入您的过滤器
import com.example.mqttmanage.config.JwtUtil; // 确保导入您的 JwtUtil
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService; // 确保导入
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private JwtUtil jwtUtil; // 注入 JwtUtil

    @Autowired
    private UserDetailsService userDetailsService; // 注入 UserDetailsService

    // 用于密码加密的 Bean
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 配置 AuthenticationManager (如果需要)
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    // 配置安全过滤链
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 禁用 CSRF，因为是无状态 API
                .csrf(AbstractHttpConfigurer::disable)
                // 禁用 Session，因为使用 Token
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 配置授权规则
                .authorizeHttpRequests(authz -> authz
                        .requestMatchers("/auth/**","/communication/upload").permitAll() // /auth/** 路径下的所有请求都允许匿名访问
                        .anyRequest().authenticated() // 其他所有请求都需要认证
                )
                // 添加 JWT 过滤器，在 UsernamePasswordAuthenticationFilter 之前
                .addFilterBefore(new JwtTokenFilter(jwtUtil, userDetailsService), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}